import ccxt from 'ccxt';

export default class BinanceService {
    static binance;

    static getInestance() {
        if (!BinanceService.binance) {
            BinanceService.init();
        }

        return BinanceService.binance;
    }

    static init() {
        // 初始化交易所客户端
        BinanceService.binance = new ccxt.binance({
            enableRateLimit: true, // 自动处理频率限制（必选）
            timeout: 15000,       // 超时时间（毫秒）
        });
    }

    //获取货币对信息
    static async getSymbolsInfo(symbolArray) {
        let binance = BinanceService.getInestance();

        // 确保市场数据已加载
        if (!binance.markets) {
            try {
                await binance.loadMarkets();
            } catch (error) {
                console.error('Error loading markets:', error);
                return null;
            }
        }

        // 过滤出有效的货币对
        const validSymbols = symbolArray.filter(symbol => this.binance.markets[symbol]);
        if (validSymbols.length === 0) {
            console.warn('No valid symbols to fetch.');
            return null;
        }

        let tickerList = [];
        try{
            tickerList = await this.binance.fetchTickers(validSymbols);
        }catch (error) {
            console.error('Error fetching ticker data:', error);
            return null;
        }
            
        return tickerList
    }

}